<?php
// 引入配置文件
include("config.php");

// 检查数据库连接
if (!$connect) {
    die("数据库连接失败: " . mysqli_connect_error());
}

// 构建查询条件
$whereClause = [];
if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
    $keyword = mysqli_real_escape_string($connect, $_GET['keyword']);
    // 只查询存在的字段，移除isbn
    $whereClause[] = "(name LIKE '%$keyword%')";
}

if (isset($_GET['category']) && !empty($_GET['category'])) {
    $category = mysqli_real_escape_string($connect, $_GET['category']);
    $whereClause[] = "type = '$category'";
}

if (isset($_GET['status']) && !empty($_GET['status'])) {
    $status = mysqli_real_escape_string($connect, $_GET['status']);
    $whereClause[] = "status = '$status'";
}

// 组合WHERE子句
$where = !empty($whereClause) ? "WHERE " . implode(" AND ", $whereClause) : "";

// 执行总记录数查询
$sql_count = "SELECT COUNT(*) as total FROM info_book $where";
$result_count = mysqli_query($connect, $sql_count);

// 检查查询是否成功
if (!$result_count) {
    echo "SQL查询: " . $sql_count . "<br>";
    die("总记录数查询执行失败: " . mysqli_error($connect));
}

// 获取总记录数
$row = mysqli_fetch_assoc($result_count);
$recordcount = $row['total'];
$pagesize = 6; // 每页显示6条记录
$pagecount = ceil($recordcount / $pagesize); // 使用ceil函数确保页数正确

// 获取当前页码
$pageno = isset($_GET["pageno"]) ? intval($_GET["pageno"]) : 1;

// 确保页码在有效范围内
if ($pageno < 1) {
    $pageno = 1;
}
if ($pageno > $pagecount) {
    $pageno = $pagecount;
}

// 计算分页偏移量
$startno = ($pageno - 1) * $pagesize;

// 执行分页查询
$sql = "SELECT * FROM info_book $where ORDER BY id LIMIT $startno, $pagesize";
$result = mysqli_query($connect, $sql);

// 检查查询是否成功
if (!$result) {
    echo "SQL查询: " . $sql . "<br>";
    die("分页查询执行失败: " . mysqli_error($connect));
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图书管理系统</title>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3b82f6',
            secondary: '#10b981',
            accent: '#8b5cf6',
            dark: '#1e293b',
            light: '#f8fafc',
            danger: '#ef4444',
            warning: '#f59e0b',
            info: '#06b6d4',
            success: '#10b981',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .btn {
        @apply px-4 py-2 rounded-lg font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2;
      }
      .btn-primary {
        @apply bg-primary text-white hover:bg-primary/90 focus:ring-primary;
      }
      .btn-secondary {
        @apply bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-400;
      }
      .btn-danger {
        @apply bg-danger text-white hover:bg-danger/90 focus:ring-danger;
      }
      .btn-warning {
        @apply bg-warning text-white hover:bg-warning/90 focus:ring-warning;
      }
      .btn-success {
        @apply bg-success text-white hover:bg-success/90 focus:ring-success;
      }
      .card {
        @apply bg-white rounded-xl shadow-md overflow-hidden transition-all duration-300 hover:shadow-lg;
      }
      .input {
        @apply px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all duration-200;
      }
      .badge {
        @apply px-2 py-1 text-xs font-medium rounded-full;
      }
      .badge-success {
        @apply bg-green-100 text-green-800;
      }
      .badge-warning {
        @apply bg-yellow-100 text-yellow-800;
      }
      .badge-danger {
        @apply bg-red-100 text-red-800;
      }
      .badge-info {
        @apply bg-blue-100 text-blue-800;
      }
      .search-wrapper {
        @apply relative;
      }
      .search-input {
        @apply pl-4 pr-24 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all duration-200 w-full;
      }
      .search-button {
        @apply absolute right-1.5 top-1/2 transform -translate-y-1/2 bg-primary text-white px-4 py-1.5 rounded-lg hover:bg-primary/90 transition-colors flex items-center justify-center h-[calc(100%-8px)];
      }
      .book-item {
        @apply transition-all duration-300 hover:shadow-md;
      }
      .book-item-expanded {
        @apply h-60;
      }
      .book-cover {
        @apply h-16 w-12 object-cover rounded-md;
      }
      .book-cover-expanded {
        @apply h-32 w-24;
      }
      .book-item-uniform {
        @apply h-auto; /* 让高度自动适应内容 */
      }
      .book-cover-uniform {
        @apply h-auto w-auto; /* 让图片大小自动适应容器 */
      }
    }
  </style>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen">
  <main class="p-6">
    <div class="max-w-7xl mx-auto">
      <!-- 搜索筛选栏 -->
      <div class="bg-white rounded-xl shadow-sm p-4 mb-6">
        <form id="searchForm" method="GET" action="">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">搜索</label>
              <div class="search-wrapper">
                <input type="text" id="searchKeyword" name="keyword" class="search-input" placeholder="输入书名" value="<?php echo isset($_GET['keyword']) ? htmlspecialchars($_GET['keyword']) : ''; ?>">
                <button type="submit" class="search-button">
                  <i class="fa fa-search mr-1"></i> 搜索
                </button>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">图书类别</label>
              <select id="searchCategory" name="category" class="input w-full">
                <option value="">全部类别</option>
                <option value="文学" <?php echo (isset($_GET['category']) && $_GET['category'] == '文学') ? 'selected' : ''; ?>>文学</option>
                <option value="计算机" <?php echo (isset($_GET['category']) && $_GET['category'] == '计算机') ? 'selected' : ''; ?>>计算机</option>
                <option value="历史" <?php echo (isset($_GET['category']) && $_GET['category'] == '历史') ? 'selected' : ''; ?>>历史</option>
                <option value="经济" <?php echo (isset($_GET['category']) && $_GET['category'] == '经济') ? 'selected' : ''; ?>>经济</option>
                <option value="哲学" <?php echo (isset($_GET['category']) && $_GET['category'] == '哲学') ? 'selected' : ''; ?>>哲学</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
              <select id="searchStatus" name="status" class="input w-full">
                <option value="">全部状态</option>
                <option value="可借阅" <?php echo (isset($_GET['status']) && $_GET['status'] == '可借阅') ? 'selected' : ''; ?>>可借阅</option>
                <option value="已借出" <?php echo (isset($_GET['status']) && $_GET['status'] == '已借出') ? 'selected' : ''; ?>>已借出</option>
                <option value="逾期" <?php echo (isset($_GET['status']) && $_GET['status'] == '逾期') ? 'selected' : ''; ?>>逾期</option>
              </select>
            </div>
          </div>
          <div class="mt-4 flex justify-end space-x-3">
            <a href="export_csv.php<?php echo isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''; ?>" class="btn btn-secondary">
              <i class="fa fa-download mr-2"></i> 导出CSV
            </a>
          </div>
        </form>
      </div>

      <!-- 图书列表 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">书名</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入库时间</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类别</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入库总量</th>
                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <?php
              if ($recordcount === 0) {
              ?>
              <tr>
                <td colspan="7" class="px-6 py-10 text-center text-gray-500">
                  <div class="flex flex-col items-center">
                    <i class="fa fa-book text-gray-300 text-5xl mb-4"></i>
                    <p>暂无图书数据</p>
                  </div>
                </td>
              </tr>
              <?php
              } else {
                $isFirstPage = ($pageno == 1);
                $previousRowHeight = null;
                while ($row = mysqli_fetch_assoc($result)) {
                  $statusClass = $row['status'] === '可借阅' ? 'badge-success' : ($row['status'] === '已借出' ? 'badge-warning' : 'badge-danger');
                  $isFirstRow = ($startno == 0 && !isset($firstRowProcessed));
                  $firstRowProcessed = true;
                  
                  // 为所有行添加统一的类
                  $uniformClass = 'book-item-uniform';
                  $coverClass = 'book-cover-uniform';
                  
                  // 为ID为3的行添加特殊标记
                  $specialMark = ($row['id'] == 3) ? 'data-target-row="true"' : '';
              ?>
              <tr class="hover:bg-gray-50 transition-colors book-item <?php echo $isFirstPage && $isFirstRow ? 'book-item-expanded' : ''; ?> <?php echo $uniformClass; ?>" data-book-id="<?php echo $row['id']; ?>" <?php echo $specialMark; ?>>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo $row['id']; ?></td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <div class="flex-shrink-0">
                      <img class="<?php echo $coverClass; ?> <?php echo $isFirstPage && $isFirstRow ? 'book-cover-expanded' : ''; ?>" src="https://picsum.photos/id/<?php echo rand(24, 40); ?>/100/150" alt="<?php echo $row['name']; ?>">
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900 <?php echo $isFirstPage && $isFirstRow ? 'text-lg' : ''; ?>"><?php echo $row['name']; ?></div>
                      <!-- 如果没有author字段，显示默认文本 -->
                      <div class="text-xs text-gray-500 <?php echo $isFirstPage && $isFirstRow ? 'text-sm' : ''; ?>">
                        <?php echo isset($row['author']) ? $row['author'] : '未知作者'; ?>
                        <span class="ml-2 <?php echo $statusClass; ?>"><?php echo $row['status']; ?></span>
                      </div>
                      <div class="text-xs text-gray-500 mt-1 <?php echo $isFirstPage && $isFirstRow ? 'text-sm' : ''; ?>">
                        <?php echo isset($row['description']) ? substr($row['description'], 0, 80) . '...' : '暂无描述'; ?>
                      </div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 <?php echo $isFirstPage && $isFirstRow ? 'text-lg font-medium' : ''; ?>">¥<?php echo $row['price']; ?></td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 <?php echo $isFirstPage && $isFirstRow ? 'text-sm' : ''; ?>"><?php echo $row['uploadtime']; ?></td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 <?php echo $isFirstPage && $isFirstRow ? 'text-sm px-3 py-1' : ''; ?>">
                    <?php echo $row['type']; ?>
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 <?php echo $isFirstPage && $isFirstRow ? 'text-lg font-medium' : ''; ?>"><?php echo $row['total']; ?></td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <a href="update_book.php?id=<?php echo $row['id']; ?>" class="text-primary hover:text-primary/80 mr-3">
                    <i class="fa fa-pencil mr-1"></i> 修改
                  </a>
                  <a href="javascript:void(0)" class="text-danger hover:text-danger/80 delete-btn" data-book-id="<?php echo $row['id']; ?>">
                    <i class="fa fa-trash mr-1"></i> 删除
                  </a>
                </td>
              </tr>
              <?php
                }
              }
              ?>
            </tbody>
          </table>
        </div>

        <!-- 分页控件 -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                显示第 <span class="font-medium"><?php echo $startno + 1; ?></span> 至 <span class="font-medium"><?php echo min($startno + $pagesize, $recordcount); ?></span> 条，共 <span class="font-medium"><?php echo $recordcount; ?></span> 条记录
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <?php if ($pageno > 1) { ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['pageno' => 1])); ?>" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                  <span class="sr-only">首页</span>
                  <i class="fa fa-angle-double-left"></i>
                </a>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['pageno' => $pageno - 1])); ?>" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                  <span class="sr-only">上一页</span>
                  <i class="fa fa-angle-left"></i>
                </a>
                <?php } else { ?>
                <span class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-gray-50 text-sm font-medium text-gray-400">
                  <span class="sr-only">首页</span>
                  <i class="fa fa-angle-double-left"></i>
                </span>
                <span class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-gray-50 text-sm font-medium text-gray-400">
                  <span class="sr-only">上一页</span>
                  <i class="fa fa-angle-left"></i>
                </span>
                <?php } ?>

                <?php
                $startPage = max(1, $pageno - 2);
                $endPage = min($pagecount, $startPage + 4);
                if ($endPage - $startPage < 4 && $startPage > 1) {
                  $startPage = max(1, $endPage - 4);
                }
                
                for ($i = $startPage; $i <= $endPage; $i++) {
                  if ($i == $pageno) {
                    echo '<span class="relative inline-flex items-center px-4 py-2 border border-primary bg-primary/10 text-sm font-medium text-primary">' . $i . '</span>';
                  } else {
                    echo '<a href="?'. http_build_query(array_merge($_GET, ['pageno' => $i])). '" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">' . $i . '</a>';
                  }
                }
                ?>

                <?php if ($pageno < $pagecount) { ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['pageno' => $pageno + 1])); ?>" class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                  <span class="sr-only">下一页</span>
                  <i class="fa fa-angle-right"></i>
                </a>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['pageno' => $pagecount])); ?>" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                  <span class="sr-only">末页</span>
                  <i class="fa fa-angle-double-right"></i>
                </a>
                <?php } else { ?>
                <span class="relative inline-flex items-center px-2 py-2 border border-gray-300 bg-gray-50 text-sm font-medium text-gray-400">
                  <span class="sr-only">下一页</span>
                  <i class="fa fa-angle-right"></i>
                </span>
                <span class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-gray-50 text-sm font-medium text-gray-400">
                  <span class="sr-only">末页</span>
                  <i class="fa fa-angle-double-right"></i>
                </span>
                <?php } ?>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-6 mt-6">
    <div class="container mx-auto px-4">
      <div class="flex flex-col md:flex-row justify-between items-center">
        <div class="mb-4 md:mb-0">
          <p class="text-sm text-gray-500">© 2025 图书管理系统. 保留所有权利.</p>
        </div>
        <div class="flex space-x-6">
          <a href="#" class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-github text-lg"></i>
          </a>
          <a href="#" class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-twitter text-lg"></i>
          </a>
          <a href="#" class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-linkedin text-lg"></i>
          </a>
        </div>
      </div>
    </div>
  </footer>

  <script>
    // 为编辑和删除按钮添加确认提示
    document.querySelectorAll('a').forEach(link => {
      if (link.href.includes('delete_book.php')) {
        link.addEventListener('click', function(e) {
          if (!confirm('确定要删除这本书吗？此操作不可撤销。')) {
            e.preventDefault();
          }
        });
      }
    });
    
    // 回车键触发搜索
    document.getElementById('searchKeyword').addEventListener('keyup', function(e) {
      if (e.key === 'Enter') {
        document.getElementById('searchForm').submit();
      }
    });
    
    // 为搜索按钮添加悬停效果
    document.querySelector('.search-button').addEventListener('mouseenter', function() {
      this.classList.add('shadow-md');
    });
    
    document.querySelector('.search-button').addEventListener('mouseleave', function() {
      this.classList.remove('shadow-md');
    });
    
    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
          behavior: 'smooth'
        });
      });
    });
    
    // 确保所有页面的行高一致
    document.addEventListener('DOMContentLoaded', function() {
      // 找到目标行（ID为3的行）和它的下一行（ID为4的行）
      const targetRow = document.querySelector('tr[data-target-row="true"]');
      const nextRow = targetRow ? targetRow.nextElementSibling : null;
      
      // 计算目标行应该使用的高度
      let targetHeight = 0;
      
      // 如果目标行和下一行都存在，使用下一行的高度
      if (targetRow && nextRow) {
        targetHeight = nextRow.offsetHeight;
      }
      // 如果只有目标行存在，使用默认高度
      else if (targetRow) {
        // 获取表格中任意一行的高度作为参考
        const sampleRow = document.querySelector('tr[data-book-id]');
        targetHeight = sampleRow ? sampleRow.offsetHeight : 80; // 默认80px
      }
      
      // 应用高度到所有页面的行
      document.querySelectorAll('tr[data-book-id]').forEach(row => {
        row.style.height = targetHeight + 'px';
        
        // 调整封面图片大小
        const cover = row.querySelector('.book-cover-uniform');
        if (cover) {
          cover.style.height = (targetHeight * 0.6) + 'px'; // 图片高度为行高的60%
          cover.style.width = (targetHeight * 0.6 * 0.8) + 'px'; // 保持图片比例
        }
      });
      
      // 存储行高到本地存储，以便其他页面使用
      localStorage.setItem('bookRowHeight', targetHeight);
    });
    
    // 监听窗口大小变化，实时调整行高
    window.addEventListener('resize', function() {
      // 从本地存储获取行高
      const targetHeight = localStorage.getItem('bookRowHeight');
      
      if (targetHeight) {
        // 应用高度到所有页面的行
        document.querySelectorAll('tr[data-book-id]').forEach(row => {
          row.style.height = targetHeight + 'px';
          
          // 调整封面图片大小
          const cover = row.querySelector('.book-cover-uniform');
          if (cover) {
            cover.style.height = (targetHeight * 0.6) + 'px';
            cover.style.width = (targetHeight * 0.6 * 0.8) + 'px';
          }
        });
      }
    });
    
    // 删除书籍的 AJAX 处理
    document.querySelectorAll('.delete-btn').forEach(button => {
      button.addEventListener('click', function() {
        const bookId = this.dataset.bookId;
        if (!confirm('确定要删除这本书吗？此操作不可撤销。')) {
          return;
        }

        // 发送 AJAX 请求
        fetch(`delete_book.php?id=${bookId}`, {
          method: 'GET',
          headers: {
            'X-Requested-With': 'XMLHttpRequest' // 标识 AJAX 请求
          }
        })
        .then(response => response.json())
        .then(data => {
          if (data.status === 'success') {
            // 删除成功：从页面中移除该行
            const row = document.querySelector(`tr[data-book-id="${bookId}"]`);
            if (row) {
              row.style.opacity = '0';
              row.style.transform = 'translateX(50px)';
              row.style.transition = 'all 0.3s ease-out';
              
              setTimeout(() => {
                row.remove();
                // 更新总记录数显示
                updateRecordCount();
              }, 300);
            }
          } else {
            alert('删除失败：' + data.message);
          }
        })
        .catch(error => {
          console.error('删除请求失败:', error);
          alert('删除失败：请检查网络连接');
        });
      });
    });
    
    // 更新总记录数显示
    function updateRecordCount() {
      const recordCountEl = document.querySelector('.text-sm.text-gray-700 span.font-medium');
      if (recordCountEl) {
        const currentCount = parseInt(recordCountEl.textContent);
        if (!isNaN(currentCount)) {
          recordCountEl.textContent = currentCount - 1;
          
          // 检查是否没有记录了
          const tableRows = document.querySelectorAll('tr[data-book-id]');
          if (tableRows.length === 0) {
            const tableBody = document.querySelector('tbody');
            tableBody.innerHTML = `
              <tr>
                <td colspan="7" class="px-6 py-10 text-center text-gray-500">
                  <div class="flex flex-col items-center">
                    <i class="fa fa-book text-gray-300 text-5xl mb-4"></i>
                    <p>暂无图书数据</p>
                  </div>
                </td>
              </tr>
            `;
          }
        }
      }
    }
  </script>
</body>
</html>    